package com.yc.d0422;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class URLDemo {
    public static void main(String[] args) throws IOException {

        String address = "http://www.hyycinfo.com/index.html";

        URL url = new URL(address);
        System.out.println("url.getProtocol() = " + url.getProtocol());
        System.out.println("url.getHost() = " + url.getHost());
        System.out.println("url.getPath() = " + url.getPath());
        System.out.println("url.getPort() = " + url.getPort());

        URLConnection conn = url.openConnection();
        //字符集
        System.out.println("conn.getContentEncoding() = " + conn.getContentEncoding());
        //资源类型
        System.out.println("conn.getContentType() = " + conn.getContentType());
        //大小
        System.out.println("conn.getContentLength() = " + conn.getContentLength());

        String diskpath = "D:\\study\\z\\d0303" + url.getFile();
        try (InputStream in = conn.getInputStream();
             FileOutputStream fos = new FileOutputStream(diskpath)){
            byte[] bytes = new byte[1024];
            int count;
            while ((count = in.read(bytes)) > -1) {
                String s = new String(bytes, 0, count);
                System.out.println(s);
                fos.write(bytes,0,count);
            }
        }

    }
}
